﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TraceThisItem.Domain;

namespace TraceThisItem.WebUI.Teams
{
	public partial class Default : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			//if (Request.QueryString["message"] == "1")
			//{
			//    labelMessage.Text = "El equipo no puede borrarse porque contiene incidencias asociadas";
			//    Response.Redirect("~/Teams/Default.aspx?");
			//}
			if (Session["message"] != null)
			{
				labelMessage.Text = Session["message"].ToString();
				Session["message"] = null;
			}

		}

		protected void TeamDetailsDataSoure_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
		{
			e.ObjectInstance = Facade.Instance;
		}

		protected void TeamGridDataSoure_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
		{
			e.ObjectInstance = Facade.Instance;
		}

		protected void UserToAddDataSource_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
		{
			e.ObjectInstance = Facade.Instance;
		}

		protected void TeamDetailsDataSoure_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
		{
			e.InputParameters["teamId"] = (int)TeamGridView.SelectedValue;
			e.InputParameters["username"] = (string)((DropDownList)TeamDetailsView.FindControl("ddlUserToAdd")).SelectedValue;
		}

		protected void TeamDetailsDataSoure_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
		{
			e.InputParameters["teamId"] = (int)TeamGridView.SelectedValue;
			e.InputParameters["username"] = (string)TeamDetailsView.SelectedValue;
		}

		protected void linkAddUserToEmptyTeam_Click(object sender, EventArgs e)
		{
			TeamDetailsView.DefaultMode = DetailsViewMode.Insert;
		}

		protected void TeamGridView_SelectedIndexChanged(object sender, EventArgs e)
		{
			TeamDetailsView.Visible = true;
		}

		protected void TeamDetailsView_DataBound(object sender, EventArgs e)
		{
			if (TeamDetailsView.DataItemCount == 0)
			{
				TeamDetailsView.ChangeMode(DetailsViewMode.Insert);
			}
		}

		protected void TeamGridDataSoure_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
		{
			var team = Facade.Instance.GetTeamById((e.InputParameters["team"] as Team).Id);
			if (team.Project.Items.Any(i => i.TeamId == team.Id))
			{
				labelMessage.Text = "El equipo no puede borrarse porque contiene incidencias asociadas";
				e.Cancel = true;
			}		
		}

	}
}